<?php
namespace app\admin\controller;
use app\service\communityService;
use app\service\deviceService;
use app\service\roominfoService;
use Swoole\Client;
use think\facade\Db;
use think\facade\Log;
use think\facade\View;

class Device extends Common{
	public function list(){

		$com = $this->pidTokenId();
		$whe=array();
        $whe[] = ["community_id",'in',$com['com_id']];
		$communitylist=(new roominfoService())->communityList($whe);
		View::assign('communitylist',$communitylist);

        $data = request()->get();
        if (!empty($data)){
            if(!empty($data['community_id'])){
                $whe['community_id'] = $data['community_id'];//小区名称
            }


            if(!empty($data['device_name'])){
                $whe[] = ["device_name","like","%".$data['device_name']."%"];
            }

            if(!empty($data['device_type'])){
                $whe['deviceType'] = $data['device_type'];
            }

            View::assign('where',$whe);
            $whe= array_filter($whe);
        }else{
            //$whe = null;
        }
        $page = request()->has('page') ? request()->get('page') : 1;
        $pagelist = (new deviceService())->getList($page,$whe);
        $number = (new deviceService())->number($whe);
        if(!empty($number)){
            foreach($pagelist as $lis){
                $info=Db::table("device_client_login")->where("device_id",$lis["id"])->find();
                if(empty($info)){
                    $lis["connect_status"]="离线";
                }else{
                    $lis["connect_status"]="在线";
                }
                $list[] = $lis;
            }
            View::assign('list', $list);
        }else{
            View::assign('list', $communitylist);
        }
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }

        View::assign('number',$number);
		//View::assign("list",$pagelist);
        View::assign("pagelist",$pagelist);
		return View::fetch("list");
	}

	public function add(){
        //查询服务商信息
        $com = $this->pidTokenId();
        $where[]=['id','in',$com['com_id']];
        $communitylist =(new communityService())->communityList($where);
        View::assign('communitylist',$communitylist);
        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();

            //if(empty($data["c"]))

            $info = Db::table("device")
                ->where("community_id",$data["community_id"])
                ->where("devicekey",$data["devicekey"])
                ->find();
            if($info){
                $this->error('该设备序列号已添加');
            }

            $community_info=Db::table("community") ->where("id",$data["community_id"])->find();
            //插入数据到数据库S
            $add["community_id"]=$data["community_id"];
            $add["devicekey"]=$data["devicekey"];
            $add["imei"]=$data["imei"];
            $add["deviceType"]=$data["deviceType"];
            $add["lockname"]=$data["lockname"];
            $add["group"]=$data["group"];
            $add["building"]=$data["building"];
            $add["unit"]=$data["unit"];
            $add["community_name"]=$community_info["community_name"];
            $result = (new deviceService())->add($add);
            if($result){
                return "添加成功";
            }else{
                $this->error('添加失败',url('add'));
            }
        }
        return View::fetch('add');
		
	}
    public function edit(){
        if(request()->isGet()){
            $id = request()->param('id');
            if(!isset($id) && empty($id)){
                $this->error('设备信心不存在');
            }
            $info = (new deviceService())->getInfo($id);
            View::assign('info',$info);
            return View::fetch('edit');
        }else{
            $data = request()->post();
            $validate=  $this->validate($data,[
                'devicekey|设备序列号' => 'require',

            ]);
            if($validate !== true){
                $this->error($validate);
            }
            if(!empty($data["qrcode_id"])){
                $res=Db::name('device')
                    ->where("id","<>",$data["id"])
                    ->where("qrcode_id",$data["qrcode_id"])->find();
                if(!empty($res)){
                    $this->error('二维码id不能重复');
                }
            }
            //var_dump($data);exit;
            $result = (new deviceService())->edit($data);
            if($result){
                return "修改成功";
                $this->success('修改成功',url('list'));
            }else{
                $this->error('修改失败');
            }
        }
    }
    public function open(){
        $id=request()->get("id");
        $deviceInfo=(new deviceService())->getInfo($id);
        if(empty($deviceInfo)){
            return "设备信息不存在";
        }
        $clientInfo=Db::table("device_client_login")->where("imei",$deviceInfo["imei"])->find();
        if(empty($clientInfo)){
            return "模组信息配置错误或不在线";
        }
        //开闸
        $client=new Client(SWOOLE_SOCK_TCP);
        if ($client->connect("127.0.0.1",9500)) {
            $open["fd"]=$clientInfo["fd"];
            $open["command"]="open";
            $open["imei"]=$clientInfo["imei"];
            $client->send(json_encode($open)); // 发送数据到服务器
            $response = $client->recv(); // 接收服务器响应数据
            Log::record('Received from server: ' . $response); // 记录日志或返回给用户等操作...
            $client->close(); // 关闭连接
            echo $response."\r\n";
            return "开闸成功";
        } else {

            Log::record('Failed to connect to the server.'); // 连接失败处理...
            return "开闸失败";
        }
    }

    public function del(){
        $id=request()->param("id");
        $deviceInfo=(new deviceService())->getInfo($id);
        if(empty($deviceInfo)){
            return "设备信息不存在";
        }
        $res=Db::table("device")->where("id",$id)->delete();
        if($res){
            $this->success('修改成功',url('list'));
        }else{
            $this->error('设备信心不存在');
            return json(["success"=>"删除失败"]);
        }

    }
}